package com.zyx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zyx.constants.Constants;
import com.zyx.constants.ChannelMap;
import com.zyx.service.RedisService;
import com.zyx.service.ResponseMsgService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

import static com.zyx.constants.Constants.*;

/**
 * 描述说明: 设备响应报文解析
 *
 * @author DQing
 * @version 1.0
 * @className DeviceResponseMsgServiceImpl
 * @date 2020/3/31 17:47
 */
@Slf4j
@Service
public class DeviceResponseMsgServiceImpl implements ResponseMsgService {
    @Autowired
    RedisService redisService;

    @Override
    public String msgType() {
        return Constants.DEVICE_BASIC_INFO_URI;
    }

    @Override
    public void parseMsg(ChannelHandlerContext ctx,Map<String, Object> jsonMap) {
        log.info("# 解析设备查询响应报文-start");
        JSONObject data = (JSONObject) jsonMap.get(DEVICE_DATA);
        String deviceNo = data.getString(DEVICE_CODE);
        if(!StringUtils.isEmpty(deviceNo)){
            ChannelMap.addDeviceChannel(deviceNo,ctx.channel());
            Object cacheData = redisService.get(REDIS_PREFIX+deviceNo);
            if(StringUtils.isEmpty(cacheData)){
                ctx.close();
            }
            String address = data.getString(DEVICE_ADDRESS);
            redisService.set(REDIS_PREFIX+deviceNo,address);
            log.info("# 解析设备查询响应报文，设备地址:{}",address);
        }
    }
}
